package com.xdf.wxbebarrel.controller;

import com.xdf.wxbebarrel.model.User;
import com.xdf.wxbebarrel.model.UserMill;
import com.xdf.wxbebarrel.service.ReqsLogService;
import com.xdf.wxbebarrel.service.UserMillService;
import com.xdf.wxbebarrel.service.UserService;
import com.xdf.wxbebarrel.utils.BusinessException;
import com.xdf.wxbebarrel.utils.JsonResult;
import com.xdf.wxbebarrel.utils.WechatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WechatUtils wechatUtils;
    @Autowired
    private ReqsLogService dbLog;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMillService userMillService;

    @GetMapping("/test")
    public JsonResult test(){
        return JsonResult.ok("wechat接口测试成功");
    }

    @GetMapping("")
    public String checkSignature(HttpServletRequest request, HttpServletResponse response){
        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echostr = request.getParameter("echostr");

        String tip = "signature = " + signature + ",nonce = " + nonce + ", timestamp = " + timestamp + ", echostr = " + echostr;
        dbLog.insert(tip,"腾讯服务器要求验证我方服务器的合法性");

        if(wechatUtils.check(timestamp,nonce,signature)){
            dbLog.insert("我方服务器验证通过，即将响应");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(echostr);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else{
            dbLog.insert("签名验证失败");
        }
        return null;
    }

    @PostMapping("")
    public void handleRequest(HttpServletRequest request,HttpServletResponse response) throws IOException {
        dbLog.insert(request.getInputStream().toString(),"入口接口post方法接收到请求");
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");

//        wechatUtils.setResponse(response);
        String resXML = wechatUtils.getResponse(request.getInputStream());
        dbLog.insert(resXML,"入口接口post方法的响应");
        PrintWriter out = response.getWriter();
        out.print(resXML);
        out.flush();
        out.close();
    }

    @GetMapping("/getWxJsApiConfigs/**")
    public JsonResult getWxJsApiConfigs(HttpServletRequest req) throws IOException {
        dbLog.insert(req.toString(),"调用微信JS API传入的参数");

        String path = req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        String path2 = req.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
        String param = new AntPathMatcher().extractPathWithinPattern(path2,path);

        dbLog.insert(path,"path");
        dbLog.insert(path2,"path2");
        dbLog.insert(param,"param");

        String code = req.getParameter("code");
        String state = req.getParameter("state");
        dbLog.insert("code=" + code + ",state=" + state,"HttpServletRequest请求中的两个参数");

        int startIndex = param.indexOf("www");
        String suffix = param.substring(startIndex);
        String fullUrl = "https://" + suffix;
        if( code !=null && code.length()>0 )
            fullUrl = "https://" + suffix + "?code=" + code + "&state=" + state;

        dbLog.insert(fullUrl,"完整的请求URL");
        return JsonResult.ok(wechatUtils.getWxJsApiConfigs(fullUrl));
    }

    @GetMapping("/openid/{code}")
    public JsonResult getOpenid(@PathVariable String code) throws IOException {
        return JsonResult.ok(wechatUtils.getOpenidByOAuth(code));
    }

    // 根据前端页面传递来的 code 先获取  openId 在获取 user
    @GetMapping("/user/{code}")
    public JsonResult getUser(@PathVariable String code) throws IOException {
        String openId = wechatUtils.getOpenidByOAuth(code);
        if(openId == null || openId.length() == 0) throw new BusinessException("获取用户信息失败，无法鉴权，无权查看该页面！");
        User user = userService.selectByOpenId(openId);
        if(user == null) throw new BusinessException("获取用户信息失败，无法鉴权，无权查看该页面！");
        return JsonResult.ok(user);
    }

    @GetMapping("/userMill/{code}")
    public JsonResult getUserMill(@PathVariable String code) throws IOException {
        String openId = wechatUtils.getOpenidByOAuth(code);
        if(openId == null || openId.length() == 0) throw new BusinessException("获取用户信息失败，无法鉴权，无权查看该页面！");
        List<UserMill> userMills = userMillService.selectByOpenId(openId);
        if(userMills == null || userMills.size() == 0) throw new BusinessException("获取用户信息失败，无法鉴权，无权查看该页面！");
        return JsonResult.ok(userMills);
    }
}
